<?
 if(ereg("FileUpload.class",$_SERVER['PHP_SELF'])) exit();
class FileUpload{

	var $fileName;
	var $fileType;
	var $fileSize;
	var $fileTypeAllowed;
	var $dirPath;
	var $overwrite;
	var $maxSize;
	var $imageType="image/x-png,image/png,image/pjpeg,image/jpeg,image/bmp,image/gif";
	var $textType="application/msword,application/vnd.ms-powerpoint,text/plain,application/vnd.ms-excel,application/pdf,text/richtext";
	var $appType="application/octet-stream";
	
	function initialize($in_dir,$in_fileTypeAllowed="all",$in_maxSize){
		$this->dirPath=$in_dir;
		if ($in_fileTypeAllowed=="image") {
			$this->fileTypeAllowed= $this->imageType;
		} else if ($in_fileTyeAllowed=="text") {
			$this->fileTypeAllowed= $this->textType;
		} else if ($in_fileTypeAllowed=="application"){
			$this->fileTypeAllowed= $this->appType;
		} else if ($in_fileTypeAllowed=="all") {
			$this->fileTypeAllowed=$this->imageType.",".$this->textType.",".$this->appType;
		}
		$this->maxSize=$in_maxSize;
		if(!is_dir($this->dirPath)){
			echo "directory not exists!";
		}
	}
	
	function upload($file,$newFileName,$overwrite){
		$this->fileName=$file['name'];
		$this->fileType=$file['type'];
		$this->fileSize=$file['size'];
		$this->fileTmp=$file['tmp_name'];
		if(substr($newFileName,strlen($newFileName)-4,1)!="."){
			$this->newFileName=$newFileName.".".substr($this->fileName,strlen($this->fileName)-3,3);
		} else {
			$this->newFileName=$newFileName;
		}
		$this->overwrite=$overwrite;
		
		if (!ereg($this->fileType,$this->fileTypeAllowed)){
			echo $this->fileType."-".$this->fileTypeAllowed;
			return "file type is not allowed";
		} else if ($this->fileSize>$this->maxSize) {
			return "file size is exceed maximum size allowed";
		} else {
			if($overwrite==true){
				if (is_uploaded_file($this->fileTmp)) {
						if (file_exists($this->fileName)) {
								unlink($this->fileName);
						}
						$result=copy($this->fileTmp,$this->dirPath."/$this->newFileName");
						if($result) {
								unlink($this->fileTmp);
								return "file upload successfull";
						} else {
								return "file upload failed";
						}
						
						
				} else {
						return "file upload failed";
				}				
			} else {
				return "file already exist";
			}
		}
	}

}
?>